package com.ce.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ce.server.common.AdminVo;
import com.ce.server.common.RespBean;
import com.ce.server.common.RespPageBean;
import com.ce.server.pojo.*;
import com.ce.server.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 郑爽
 * @since 2021-11-14
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

  @Autowired
  private IAdminService adminService;
  @Autowired
  private IAliOssService aliOssService;
  @Autowired
  private INationService nationService;
  @Autowired
  private IPositionService positionService;
  @Autowired
  private IPoliticsStatusService politicsStatusService;
  @Autowired
  private IOperlogService operlogService;


  @ApiOperation(value = "更新用户信息")
  @PutMapping("/")
  public RespBean updateAccoutInfo(@RequestBody Admin admin) {

    return adminService.updateAccountInfo(admin) ? RespBean.success("更新成功") : RespBean.error("更新失败");
  }

  @ApiOperation(value = "分页查询用户信息")
  @GetMapping("/")
  public RespPageBean getAdminsByPage(@RequestParam(defaultValue = "1") Integer currentPage,
                                      @RequestParam(defaultValue = "10") Integer size,
                                      Admin admin) {
    return adminService.getAdminsByPage(currentPage, size, admin);
  }

  @ApiOperation(value = "添加操作员")
  @PostMapping("/")
  public RespBean addAdmin(@RequestBody Admin admin) {

    return adminService.addAdmin(admin);
  }

  @ApiOperation(value = "删除操作员")
  @DeleteMapping("/{id}")
  public RespBean delAdmin(@PathVariable("id") String wno) {
    return adminService.delAdminByWno(wno) > 0 ? RespBean.success("删除操作员成功！") : RespBean.error("删除操作员失败！");
  }

  @ApiOperation(value = "更新操作员角色")
  @PutMapping("/role")
  public RespBean updateAdminRole(String adminWno, Integer[] rids) {

    return adminService.updateAdminRole(adminWno, rids);
  }

  @ApiOperation(value = "获取最大操作员工号")
  @GetMapping("/maxId")
  public RespBean getAdminMaxId() {
    return adminService.getAdminMaxId();
  }

  @ApiOperation(value = "测试文件上传oss")
  @PostMapping("/upload")
  public RespBean upload(MultipartFile file){
    String upload = aliOssService.upload(file);
    return RespBean.success(upload);
  }

  @ApiOperation(value = "导出校职工信息")
  @GetMapping(value = "/export",produces = "application/octet-stream")
  public void exportAdminsInfo(HttpServletResponse response){
    List<AdminVo> admin_list = adminService.getAllRecords();
    ExportParams exportParams = new ExportParams("校职工信息表", "校职工信息表", ExcelType.HSSF);
    // 导出工具类
    Workbook workbook = ExcelExportUtil.exportExcel(exportParams, AdminVo.class, admin_list);
    ServletOutputStream outputStream = null;
    try {
      // 用流的形式传输
      response.setHeader("content-type", "application/octet-stream");
      // 防止中文乱码
      response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("校职工信息表.xls", "UTF-8"));
      outputStream = response.getOutputStream();
      workbook.write(outputStream);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (null != outputStream) {
        try {
          outputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  @ApiOperation(value = "导入校职工数据")
  @PostMapping("/import")
  public RespBean importStudent(MultipartFile file) {
    ImportParams importParams = new ImportParams();
    // 去掉第一行标题
    importParams.setTitleRows(1);
    // 获取实体数据
    List<Nation> nation_list = nationService.list();
    List<PoliticsStatus> politicsStatus_list = politicsStatusService.list();

    try {
      List<Admin> adminRecords = ExcelImportUtil.importExcel(file.getInputStream(), Admin.class, importParams);
      adminRecords.forEach(admin -> {
        admin.setNationId(nationService.getOne(new LambdaQueryWrapper<Nation>().eq(Nation::getName, admin.getNation().getName())).getId());
        admin.setPoliticId(politicsStatusService.getOne(new LambdaQueryWrapper<PoliticsStatus>().eq(PoliticsStatus::getName, admin.getPoliticsStatus().getName())).getId());
        admin.setPosId(positionService.getOne(new LambdaQueryWrapper<Position>().eq(Position::getName,admin.getPosition().getName())).getId());
      });
      if (adminService.saveBatch(adminRecords)) {
        return RespBean.success("数据插入成功！");
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    return RespBean.error("数据插入失败！");
  }

  @ApiOperation("根据工号查询员工信息")
  @GetMapping("/wno/{wno}")
  public RespBean getRecordByWno(@PathVariable String wno){
    Admin admin = adminService.getOne(new LambdaQueryWrapper<Admin>().eq(Admin::getWno, wno));
    if (admin!=null){
      AdminVo adminVo = new AdminVo().setWno(admin.getWno()).setWname(admin.getWname());
      return RespBean.success("查询成功！",adminVo);
    }
    return RespBean.error("不存在该工号");


  }
}
